# -*- coding:utf8 -*-
"""
执行入口
"""
from __future__ import print_function, unicode_literals
import os

from whoosh.index import open_dir, create_in, exists_in
from whoosh.fields import Schema, TEXT, KEYWORD, ID, STORED, NUMERIC
from whoosh.qparser import QueryParser

from logger_utility.loggconfig import getLogger


class TextEngine(object):
    """
    搜索引擎
    """

    logger = getLogger('WhooshWhoosh')

    def __init__(self,
                 schema=Schema(
                     title=KEYWORD(stored=True),
                     id=ID(stored=True)
                 ),
                 path=None,
                 name=None,
                 tag=None):
        """
        加载模型
        """
        self.path = path
        self.name = name
        self.schema = schema
        self.tag = tag
        if self.path:
            self.load()

    def load(self, path=None, name=None):
        """
        加载
        """
        if not path:
            path = self.path
        if not name:
            name = self.name

        if name:
            if exists_in(path, name):
                self.ix = open_dir(path, indexname=name)
                self.logger.info(
                    "Load Whoosh Search Indexer (%s, %s)", path, name)
            else:
                self.ix = create_in(path, self.schema, indexname=name)
                self.logger.info(
                    "Create Whoosh Search Indexer (%s, %s)", path, name)
        else:
            if exists_in(path):
                self.ix = open_dir(path)
                self.logger.info(
                    "Load Whoosh Search Indexer (%s, %s)", path, name)
            else:
                self.ix = create_in(path, self.schema)
                self.logger.info(
                    "Create Whoosh Search Indexer (%s, %s)", path, name)

    def add(self, docs):
        """
        添加语料
        """
        writer = self.ix.writer()
        for title, id_ in docs:
            writer.add_document(
                title=title,
                id=unicode(id_)
            )

        writer.commit()

    def remove(self, docs):
        """
        删除
        """
        writer = self.ix.writer()
        for id_ in docs:
            writer.delete_by_term('id', unicode(id_))

        writer.commit()

    def search_words(self, words, limit=200):
        """
        查询
        """
        with self.ix.searcher() as searcher:
            qp = QueryParser("title", schema=self.ix.schema)
            q = qp.parse(' OR '.join(words))
            ret = searcher.search(q, limit=limit)
            result = []
            for i in ret:
                result.append((int(i['id']), i['title']))
        return result
